import Taro from '@tarojs/taro'
import app from '../../../main.js'
let myJs = {
    getData: function() {
        this.state = {
            submitState: false,
            page: 1,
            isOpened: false,
            message: '',
            case_course: {
                id: '',
                case_id: '',
                type: '',
                visit_at: app.dateFormate(new Date(), "yyyy-MM-dd"),
                result: ''
            },
            case_template: {
                id:'',
                name: '',
                content: '',
                project_id: ''
            },
            template: [
                
            ],
            result: {
                courseTemplateId: 1,
                subjects: {}
            },
            tempImg: '',
            text: '',
            imgModal: false,
        };
        return this.state;
    },
    imageChange2() {
        var me = this;
        wx.chooseImage({
            count: 1,
            sizeType: ['original'],
            sourceType: ['album', 'camera'],
            success(res) {
                const tempFilePaths = res.tempFilePaths;
                me.state.tempImg = tempFilePaths[tempFilePaths.length - 1];
                me.setState({
                    imgModal: true,
                    text: ''
                });
            }
        })
    },
    deleteImage(url, id) {
        var me = this;

        var result = me.state.result;
        var list = result.subjects[id].value;
        var value = [];
        for (var i = 0; i < list.length; i++) {
            if (list[i].url != url) {
                value.push(list[i]);
            }
        }

        result.subjects[id].value = value;
        me.setState({
            result: result
        });
    },
    closeModal() {
        this.setState({
            imgModal: false,
            tempImg: ''
        });
    },
    comfirmModal(id) {
        var me = this;
        if(!this.state.text) {
            Taro.showToast({
                title: '请输入照片名称',
                icon: 'none',
                duration: 2000
            })
            return;
        }

        Taro.showLoading({
            title: '上传中...',
            mask: true
        })

        wx.uploadFile({
            url: app.apiUri + '/admin/upload/image',
            filePath: me.state.tempImg,
            name: 'file',
            formData: {
              name: 'file'
            },
            success(res) {
              Taro.hideLoading();
              if (res.statusCode == 413) {
                app.toast('文件过大，请重新上传');
                return;
              }
              let data = JSON.parse(res.data);
              if (data.status == 200) {
                var result = me.state.result;
                var value = !result.subjects[id].value ? [] : result.subjects[id].value;
                value.push({url: app.getPath(data.result), text: me.state.text});
                result.subjects[id].value = value;
                me.setState({
                    result: result,
                    imgModal: false,
                    tempImg: ''
                });
              }
            }
          })
    },
    getCaseTemplate(name) {
        var me = this;
        app.get("api/case_templates/getByName2", {name: me.$router.params.course_name, id: me.$router.params.case_template_id}, function(res) {
            var template = [];
            template = JSON.parse(res.data.result.content);
            for(var i = 0; i < template.length; i++) {
                for(var t = 0; t < template[i].subjects.length;t++) {
                    var item = template[i].subjects[t];
                    if(item.type == "多选题") {
                        me.state.result.subjects[item.id] = {value: {v1: [], v2: ''}};
                        me.state.result.subjects[item.id].options = item.options;
                    } else if(item.type == "矩阵填空题") {
                        me.state.result.subjects[item.id] = {value: {}};
                        me.state.result.subjects[item.id].items = item.items;
                        for(var k = 0; k < item.items.length; k++) {
                            me.state.result.subjects[item.id].value["v"+(k+1)] = "";
                        }
                    } else if(item.type == "矩阵单选题") {
                        me.state.result.subjects[item.id] = {value: {}};
                        me.state.result.subjects[item.id].xItems = item.xItems;
                        me.state.result.subjects[item.id].yItems = item.yItems;
                        for(var k = 0; k < item.yItems.length; k++) {
                            me.state.result.subjects[item.id].value["v"+(k+1)] = "";
                        }
                    }  else if(item.type == "矩阵多选题") {
                        me.state.result.subjects[item.id] = {value: {}, state: []};
                        for(var k = 0; k < item.yItems.length; k++) {
                            me.state.result.subjects[item.id].value["v"+(k+1)] = "";
                            var xc = [];
                            for(var j = 0; j < item.xItems.length; j++) {
                                me.state.result.subjects[item.id].state.push(xc);
                            }
                        }
                    } else if(item.type == "上传图片") {
                        me.state.result.subjects[item.id] = {value: {}, state: []};
                        me.state.result.subjects[item.id].items = item.items;
                        for(var k = 0; k < item.items.length; k++) {
                            me.state.result.subjects[item.id].value["v"+(k+1)] = [];
                            me.state.result.subjects[item.id].state.push(true);
                        }
                    } else if(item.type == "单选题") {
                        me.state.result.subjects[item.id] = {value: {v1: '', v2: ''}};
                        me.state.result.subjects[item.id].options = item.options;
                    } else if(item.type == "眼科检查") {
                        var temp = item.displays.split(',');
                        var displays = {};
                        for(var l = 0; l < temp.length; l++) {
                            displays[temp[l]] = true;
                        }
                        me.state.result.subjects[item.id] = { displays: displays, value: {
                            'v1': {
                                '裸眼视力': {'v1': '', 'v2': '', 'v3': '', 'v4': ''}, 
                                '矫正视力': {'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '光定位':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '色觉':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '眼睑':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '睫毛':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '眼位':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '眼球':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '结膜':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '泪道冲洗':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '胬肉':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '角膜':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '前房':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '虹膜':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '瞳孔':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '晶状体':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '玻璃体':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '眼底':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '眼压':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                'A超B超':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '拱高':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '内皮细胞数':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '光焦度':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '术后裸眼视力':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '散瞳验光':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '术前最佳矫正视力':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '术前眼压（mmHg）':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '前房深度ACD（mm）':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '角膜内皮细胞计数（个/mm2）':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                            }, 
                            'v2': {
                                '裸眼视力': {'v1': '', 'v2': '', 'v3': '', 'v4': ''}, 
                                '矫正视力': {'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '光定位':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '色觉':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '眼睑':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '睫毛':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '眼位':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '眼球':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '结膜':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '泪道冲洗':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '胬肉':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '角膜':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '前房':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '虹膜':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '瞳孔':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '晶状体':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '玻璃体':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '眼底':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '眼压':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                'A超B超':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '拱高':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '内皮细胞数':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '光焦度':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '术后裸眼视力':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '散瞳验光':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '术前最佳矫正视力':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '术前眼压（mmHg）':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '前房深度ACD（mm）':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                                '角膜内皮细胞计数（个/mm2）':{'v1': '', 'v2': '', 'v3': '', 'v4': ''},
                            }
                        }};
                    } else {
                        me.state.result.subjects[item.id] = {value: ''};
                    }
                    me.state.result.subjects[item.id].type = item.type;
                    me.state.result.subjects[item.id].label = item.label;
                    me.state.result.subjects[item.id].required = item.required ? item.required : 0;
                }
            }

            me.state.result.courseTemplateId = res.data.result.id;
            me.setState({
                case_template: res.data.result,
                template: template,
                result: me.state.result
            },()=>{
                if(me.state.case_course.id) {
                    me.getCourse();
                }
            });
        });
    },
    createCourse() {
        var me = this;
        if(!me.state.case_course.visit_at) {
            me.showToast('请选择就诊日期');
            return;
        }
        var subjects = this.state.result.subjects;
        me.state.case_course.case_template_id = this.state.result.courseTemplateId;
        me.state.case_course.result = JSON.stringify(this.state.result);
        if (!me.checkCourse(subjects)) {
            return;
        }
        app.post("api/case_details/createCourse", me.state.case_course, function(res) {
            me.setState({
                submitState: false
            });
            app.navigateBack('../editCase/editCase?id=' + me.state.case_course.case_id);
        });
    },
    checkCourse(subjects) {
        console.log(subjects);
        for (var key in subjects) {
            var obj = subjects[key];
            var required = obj.required;
            var type = obj.type;
            var label = obj.label;
            if (!required) {
                continue;
            }
            if (type == '多选题' && app.isEmpty(obj.value.v1)) {
                app.toastMessage('请选择'+'['+label+']');
                return false;
            } else if (type == '多选题' && obj.value.v1.indexOf('其他') != -1 && app.isEmpty(obj.value.v2)) {
                app.toastMessage('['+label+']'+'选择其他选项时请填写文字说明');
                return false;
            } else if (type == '填空题' && app.isEmpty(obj.value)) {
                app.toastMessage('请填写'+'['+label+']');
                return false;
            } else if (type == '矩阵单选题') {
                for (var k in obj.value) {
                    if (app.isEmpty(obj.value[k])) {
                        var index = k.replace('v', '');
                        index = parseInt(index) - 1;
                        app.toastMessage('请选择'+'['+label+'-'+obj.yItems[index]+']');
                        return false;
                    }
                }
            } else if (type == '单选题' && app.isEmpty(obj.value.v1)) {
                app.toastMessage('请选择'+'['+label+']');
                return false;
            }  else if (type == '矩阵填空题') {
                for (var k in obj.value) {
                    if (app.isEmpty(obj.value[k])) {
                        var index = k.replace('v', '');
                        index = parseInt(index);
                        app.toastMessage('请填写'+'['+label+'-'+obj.items[index]['label']+']');
                        return false;
                    }
                }
            }
        }
        return true;
    },
    updateCourse() {
        var me = this;
        var subjects = me.state.result.subjects;
        me.state.case_course.result = JSON.stringify(this.state.result);
        if (!me.checkCourse(subjects)) {
            return;
        }
        app.post("api/case_details/updateCourse", me.state.case_course, function(res) {
            me.setState({
                submitState: false
            });
            app.navigateBack('../editCase/editCase?id=' + me.state.case_course.case_id);
        });
    },
    getCourse() {
        var me = this;
        app.get("api/case_details/getCourse", {id: me.state.case_course.id}, function(res) {
            me.setState({
                case_course: res.data.result,
                result: JSON.parse(res.data.result.result)
            });
        });
    },

    imageChange(sid, rid, files) {
        var me = this;
        if(files.length == 0) {
            this.state.result.subjects[sid].value['v'+ (rid+1)] = [];
            this.state.result.subjects[sid].state[rid] = true;
            this.setState({
                result: this.state.result
            });
        } else {
            wx.uploadFile({
                url: app.apiUri + '/admin/upload/image',
                filePath: files[files.length - 1]['url'],
                name: 'file',
                formData: {
                  name: 'file'
                },
                success(res) {
                  if (res.statusCode == 413) {
                    app.toast('文件过大，请重新上传');
                    return;
                  }
                  let data = JSON.parse(res.data);
                  if (data.status == 200) {
                    me.state.result.subjects[sid].value['v'+ (rid+1)] = [{url:app.getPath(data.result)}];
                    me.state.result.subjects[sid].state[rid] = false;
                    me.setState({
                        result: me.state.result
                    });
                  }
                }
              })
        }
    },
    componentWillMount () {
        this.init();
    },
    navigateTo(url) {
        app.navigateTo(url);
    },
    navigateBack(url) {
        app.navigateBack(url);
    },
    handleDetailChange(name, event) {
        var names = name.split('.');
        var n = names[0];
        var temp = this.state;
        for(var i = 0; i < names.length - 1; i++) {
            temp = temp[names[i]];
        }

        temp[names[i]] = event.detail.value;
        this.setState({n: temp});
    },
    handleChange(name, v) {
        var names = name.split('.');
        var n = names[0];
        var temp = this.state;
        for(var i = 0; i < names.length - 1; i++) {
            temp = temp[names[i]];
        }
        
        temp[names[i]] = v;
        
        this.setState({n: temp});
    },
    handleTextareaChange(name, event) {
        var names = name.split('.');
        var n = names[0];
        var temp = this.state;
        for(var i = 0; i < names.length - 1; i++) {
            temp = temp[names[i]];
        }
        
        temp[names[i]] = event.target.value;
        this.setState({n: temp});
    },
    redirectTo(url) {
        app.redirectTo(url);
    },
    componentDidMount () {},
    componentWillUnmount () {},
    componentDidHide () {}
}
export default myJs;
